package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class DruidsUtils {

    private DruidsUtils() {
    }

    private static Map<String, Connection> map = new HashMap<>();
    private static final DruidsUtils instance = new DruidsUtils();

    /**
     *  单例获得数据连接
     *
     * @return
     */
    public static Connection getConn() {
        return getConnection();
    }

    public static Connection getConnection() {
        Properties properties = PropertyUtil.getProperties();
        DruidPooledConnection connection = null;
        if (map.get("conn") == null) {
            try {
                DruidDataSource druidDataSource = new DruidDataSource();
                assert properties != null;
                druidDataSource.setDriverClassName(properties.getProperty("jdbc.driver"));
                druidDataSource.setUrl(properties.getProperty("jdbc.url"));
                druidDataSource.setUsername(properties.getProperty("jdbc.username"));
                druidDataSource.setPassword(properties.getProperty("jdbc.password"));
                connection = druidDataSource.getConnection();
                map.put("conn", connection);
            } catch (Exception e) {
                System.out.println("获取数据库连接异常");
                e.printStackTrace();
            }
            map.put("conn", connection);
            return connection;

        } else {
            return map.get("conn");
        }

    }


}
